import React, { Component } from 'react'
import "./liveroom.scss"
import Header from '../../components/Header/header' 
import Footer from '../../components/Footer/footer'
import { getApiCoursesInfo , getApiSaveUserNote , getApiLiveInfo } from "../../axios/api"
import { get, UrlSearch } from '../../axios/localstorage'
import { message } from 'antd'

export default class liveroom extends Component {

    state = {
        type:1,
        fontList:[
            {label:"12px",size:1},
            {label:"14px",size:2},
            {label:"16px",size:3},
            {label:"18px",size:4},
            {label:"20px",size:5},
        ],
        info:{},
        data:{
            filepath:"",
            files:[],
        },
        font:'',
        text:"",
        Mudu:"",
        domPool:[],
        hasPosition:[],
        danmuPool : [],
        roomViewNum:0,
        key:"",
        id:"",
        timer:"",
        websocket:"",
        content:"<h2>公告一</h2><p>一、直播期间，请大家保持安静；</p><p>二、积极与老师互动；</p><p>三、有问题可发弹幕，直播小助理会及时回复，老师看到也会回复；</p><h2>公告一</h2><p>一、直播期间，请大家保持安静；</p><p>二、积极与老师互动；</p><p>三、有问题可发弹幕，直播小助理会及时回复，老师看到也会回复；</p>",

        color:"#1bba84",
        showColor:false,
        colors:[
            '#FF0000',
            '#FF7D00',
            '#FFFF00',
            '#00FF00',
            '#00FFFF',
            '#0000FF',
            '#FF00FF',
            '#000000',
        ]
    }

    componentWillMount(){

        let id = UrlSearch('id');
        
        let websocket  = new WebSocket("wss://zhiluedu.com.cn/wss?id="+id+'&token='+get('token'));
        // //打开事件
        websocket.onopen = function () {
            console.log("websocket已打开"); 
        }
        // //发现消息进入
        websocket.onmessage = (msg)=> {

            console.log(msg);
            console.log("websocket已连接");
            console.log(111);  // 第一次进去会显示：连接成功

            let data = JSON.parse(msg.data);

            console.log(data);

            if(data.live_id === id){
                this.addBarrage(data.msg);
            }
            
        }

        websocket.onclose = function(data) {
            console.log(data);
            console.log("websocket已关闭");
        };
        websocket.onerror = function(data) {
            console.log(data);
            console.log("websocket发生了错误");
        }

        this.setState({
            websocket,
            id
        })
    }

    componentDidMount(){

        let id = UrlSearch('id');



        // this.getTData(6);

        this.getData(id);

    }

    componentWillUnmount(){
        clearInterval(this.state.timer);
        let websocket = this.state.websocket;
        console.log('关闭websocket 123')
        websocket.close();
    }

    sendMsg=(msg)=>{
        let websocket = this.state.websocket;

        let param = {
            id:this.state.id,
            token:get('token'),
            msg:msg
        }

        websocket.send(JSON.stringify(param));
    }

    gotoSend=()=>{

        let key = this.state.key;

        
        this.sendMsg(key);
    }

    addBarrage=(text)=>{
        clearInterval(this.state.timer);
        var colors = ['#2C3E50', '#FF0000', '#1E87F0', '#7AC84B', '#FF7F00', '#9B39F4', '#FF69B4'];//弹幕颜色库
        // var text = this.state.key; //document.getElementById('text').value;
        var dmDom = document.getElementById('dm');
        // document.getElementById('text').value = "";
          var index = parseInt(Math.random() * colors.length); //随机弹幕颜色
          var screenW = dmDom.offsetWidth;
          var screenH = dmDom.offsetHeight;
          
          var max = Math.floor(screenH / 40);
          var height = 10 + 40 * (parseInt(Math.random() * (max + 1)) - 1);
          var span = document.createElement('span');
          span.style.left = screenW + 'px';
          span.style.top = height + 'px';
          span.style.color = colors[index];
          span.innerHTML = text;
          
          dmDom.appendChild(span);
          let timer = setInterval(this.move, 10);
          this.setState({
            timer,
            key:""
          })
    }

    move=()=>{
        var arr=[];
        var dmDom = document.getElementById('dm');
        var oSpan = dmDom.getElementsByTagName('span');
        for(var i=0;i<oSpan.length;i++){
          arr.push(oSpan[i].offsetLeft);
          arr[i] -= 2;
          oSpan[i].style.left = arr[i]+'px';

          if(arr[i]<-oSpan[i].offsetWidth){
            dmDom.removeChild(dmDom.childNodes[0]);
          }
        }
    }

    gotoPage=(page)=>{
        this.props.history.push(page);
    }

    getData=(id)=>{

        let param = {
            live_id:id,
            token:get('token'),
            type:get('type')?get('type'):0,
        }

        getApiLiveInfo(param)
        .then(req =>{
            if(req.data.code === 1){
                let data = req.data.data;
                if(data.filepaths){

                }else{
                    data.filepaths = [];
                }
                this.setState({
                    data
                })

                

                let play_url = data.play_url;



                window.Aliplayer({
                    "id": "player-con",
                    "source": play_url,
                    "width": "100%",
                    "height": "500px",
                    "autoplay": false,
                    "isLive": true,
                    "rePlay": false,
                    "playsinline": true,
                    "preload": true,
                    "controlBarVisibility": "hover",
                    "useH5Prism": true
                  }, function (player) {
                      console.log("The player is created");
                    }
                );

                let div = document.getElementById('textBox');
                div.innerHTML = data.note.content;
            }
        }).catch( err =>{
            console.error(err);
        })
    }

    getTData=(id)=>{
        let param = {
            id,
            token:get('token'),
        }

        getApiCoursesInfo(param)
        .then(req =>{
            if(req.data.code === 1){
                let data = req.data.data;
                if(data.files){

                }else{
                    data.files = [];
                }
                this.setState({
                    data
                })
            }
        }).catch( err =>{
            console.error(err);
        })
    }


    gotoSaveNote=()=>{

        let div = document.getElementById('textBox');
        let text = div.innerHTML;

        console.log(text);

        let param = {
            type:2,
            live_id:this.state.id,
            id:this.state.data.note?this.state.data.note.id:'',
            title:this.state.title,
            content:text,
            token:get('token'),
            types:get('type')?get('type'):0,
        }

        getApiSaveUserNote(param)
        .then(req =>{
            if(req.data.code === 1){
                message.success("保存成功！");
            }else{
                message.info(req.data.msg);
            }
        }).catch( err =>{
            console.error(err);
        })
    }

    doPrint = () => {

        const el = document.getElementById('printBox');
        const iframe = document.createElement('IFRAME');
        let ppp = document.getElementById('ppp');
        let doc = null;
        // iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:500px;top:500px;');
        ppp.appendChild(iframe);
        doc = iframe.contentWindow.document;
        // 引入打印的专有CSS样式，根据实际修改
        // doc.write('<LINK rel="stylesheet" type="text/css" href="css/print.css">');
        doc.write(el.innerHTML);
        doc.close();
        // 获取iframe的焦点，从iframe开始打印
        iframe.contentWindow.focus();
        iframe.contentWindow.print();
        if (navigator.userAgent.indexOf("MSIE") > 0)
        {
            ppp.removeChild(iframe);
        }
        
    }

    render() {
        return (
            <div className="liveroom" >
                <Header />
                <div className="cen">
                    <div className="main">
                        <div className="chead">
                            <img className="img" alt="" src="assets/imgs/dingwei.png" />
                            <p className="p_point" onClick={()=>{this.gotoPage('/')}}>首页</p>
                            <img className="icon" alt="" src="assets/imgs/xiaji.png" />
                            <p className="p_point" onClick={()=>{this.gotoPage('/live')}}>直播中心</p>
                            <img className="icon" alt="" src="assets/imgs/xiaji.png" />
                            <p className="p_point" onClick={()=>{this.gotoPage('/liveinfo?id='+this.state.id)}}>课程详情</p>
                            <img className="icon" alt="" src="assets/imgs/xiaji.png" />
                            <p>直播间</p>
                        </div>

                        <div className="minfo">
                            <div className="ileft" style={{backgroundImage:"url('"+this.state.data.thumb_text+"')"}}></div>
                            <div className="iright">
                                <div className="title">
                                    <h2>{this.state.data.title}</h2>
                                    <div hidden={!this.state.data.is_new}>精品</div>
                                </div>
                                <div className="details">
                                    <img alt="" src="assets/imgs/renhsu.png" />
                                    <p>{this.state.data.live_watch_times?this.state.data.live_watch_times:0}人</p>

                                    <img alt="" src="assets/imgs/shijain.png" />
                                    <p>{this.state.data.start_time}</p>
                                </div>
                            </div>
                        </div>

                        <div className='mbox'>
                            <div className='left' >
                                <div className='vbox' id="player-con"></div>
                                <div className='dmBox' id='dm'></div>
                            </div>
                            <div className='right'>
                                <div className='rinfo'>
                                    <div className='title'>{this.state.data.notice_title}</div>
                                    {/* <div className='rdiv'>
                                        <h2>公告一</h2>
                                        <p>一、直播期间，请大家保持安静；</p>
                                        <p>二、积极与老师互动；</p>
                                        <p>三、有问题可发弹幕，直播小助理会及时回复，老师看到也会回复；</p>
                                    </div> */}

                                    <div className="rdiv" dangerouslySetInnerHTML={{
                                        __html: this.state.data.notice
                                    }}></div>
                                </div>
                                <div className='rbom'>
                                    <textarea type="text" id='text' placeholder="发个弹幕和老师互动吧～" value={this.state.key} onChange={(ev)=>{this.setState({key:ev.target.value})}}></textarea>
                                    <div className='btnflex'>
                                        <button onClick={()=>{this.gotoSend()}}>发送</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="sleft">
                            <div className="shead">
                                <div className={this.state.type === 1?"si sactive":"si"} onClick={()=>{this.setState({type:1})}}>
                                随堂笔记
                                <div className="scen">
                                    <span></span>
                                </div>
                                </div>
                                <div className={this.state.type === 2?"si sactive":"si"} onClick={()=>{this.setState({type:2})}}>
                                课件下载
                                <div className="scen">
                                    <span></span>
                                </div>
                                </div>
                                <div className={this.state.type === 3?"si sactive":"si"} onClick={()=>{this.setState({type:3})}}>
                                课程简介
                                <div className="scen">
                                    <span></span>
                                </div>
                                </div>
                            </div>
                            <div className="ssbox" hidden={this.state.type !== 1}>
                                <div className="s1">
                                    <div className="atext" id="textBox" contentEditable="true"></div>
                                </div>
                                <div className="aoptions">
                                    <div className="aitem">
                                        <input type="button" name="" value="加粗" onClick={()=>{document.execCommand('Bold')}} />
                                        <div className="adiv">
                                            <div className="cen">
                                                <img alt="" className="icon3" src="assets/imgs/icon3.png" />
                                            </div>
                                            <p>加粗</p>
                                        </div>
                                    </div>
                                    <div className="aitem">
                                        <input type="button" name="" value="倾斜" onClick={()=>{document.execCommand('Italic')}} />
                                        <div className="adiv">
                                            <div className="cen">
                                                <img alt="" className="icon2" src="assets/imgs/icon2.png" />
                                            </div>
                                            <p>倾斜</p>
                                        </div>
                                    </div>
                                    <div className="aitem">
                                        <input type="button" name="" value="下划线" onClick={()=>{document.execCommand('Underline')}} />
                                        <div className="adiv">
                                            <div className="cen">
                                                <img alt="" className="icon4" src="assets/imgs/icon4.png" />
                                            </div>
                                            <p>下划线</p>
                                        </div>
                                    </div>
                                    <div className="aitem" onMouseEnter={()=>{this.setState({showFont:true})}} onMouseLeave={()=>{this.setState({showFont:false})}}>
                                        <div className="adiv">
                                            <div className="cen">
                                                <img alt="" className="icon1" src="assets/imgs/icon1.png" />
                                            </div>
                                            <p>字号</p>
                                        </div>

                                        <div className="sels" hidden={!this.state.showFont} >
                                            {
                                                this.state.fontList.map((item,index)=>{
                                                    return <div key={index} className={this.state.font === item.label?'hover':''} onClick={()=>{this.setState({font:item})}}>
                                                        {item.label}
                                                        <input type="button" name="" value="字体" onClick={()=>{document.execCommand('Fontsize',false,item.size)}} />
                                                        </div>
                                                })
                                            }
                                        </div>
                                    </div>
                                    <div className="aitem" onMouseEnter={()=>{this.setState({showColor:true})}} onMouseLeave={()=>{this.setState({showColor:false})}}>
                                        
                                        <div className="adiv">
                                            <div className="cen">
                                                <img alt="" className="icon1" src="assets/imgs/icon1.png" />
                                            </div>
                                            <div className="cen">
                                                <span style={{background:this.state.color}}></span>
                                            </div>
                                            <p>颜色</p>
                                        </div>

                                        <div className='color_picker' hidden={!this.state.showColor}>

                                            <div className='cbox'>
                                                {
                                                    this.state.colors.map((item,index)=>{
                                                        return <input type="button" key={index} style={{background:item}} className='cbtn' onClick={()=>{this.setState({color:item});document.execCommand("ForeColor",false,item);}} />
                                                    })
                                                }
                                                

                                            </div>
                                            
                                        </div>
                                    </div>
                                    <div className="abtns">
                                        <button className="abtn1" onClick={()=>{this.gotoSaveNote()}}>更新保存</button>
                                        <button className="abtn2" onClick={()=>{this.doPrint()}}>打印</button>
                                    </div>
                                </div>
                            </div>

                            <div className="ssbox" hidden={this.state.type !== 2}>
                                <div className="s2">
                                    {
                                        this.state.data.files.map((item,index)=>{
                                            return <div className="sdown" key={index}>
                                                        <h2>{item.title}</h2>
                                                        <a className="down" target="_blank" without rel="noreferrer" href={item.file_path} name="111" download="附件">
                                                            <img alt="" src="assets/img/xiazai.png"/>
                                                            <p>下载</p>
                                                        </a>
                                                    </div>
                                        })
                                    }
                                    
                                    <div className="snone" hidden={this.state.data.files.length !== 0}>
                                        <div className="cen">
                                            <img alt="" src="assets/imgs/wudingdan.png" />
                                        </div>
                                        <h4>暂无可下载课件</h4>
                                    </div>
                                </div>
                            </div>

                            <div className="ssbox" hidden={this.state.type !== 3}>
                                <div className="cinfo">
                                    <div className="ctitle">
                                        <img alt="" src="assets/imgs/kechenggaishu.png" />
                                        <p>课程概述</p>
                                    </div>
                                    <div className="ctext">
                                        <div className="cont" dangerouslySetInnerHTML={{
                                                __html: this.state.data.summary
                                            }}></div>
                                    </div>
                                    <div className="ctitle">
                                        <img alt="" src="assets/imgs/kechenggaishu.png" />
                                        <p>授课目标</p>
                                    </div>
                                    <div className="ctext">
                                        <div className="cont" dangerouslySetInnerHTML={{
                                                __html: this.state.data.target
                                            }}></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
                <Footer />
            </div>
        )
    }
}
